/**
 * @author yusak
 */
ChaShaKu.WordsCenterListSearch = Ext.extend(Ext.app.Module,{
	id: "wordsCenterListSearch",
	run: function(){
		this.app.modules.searchMenuButtons.centerListByWords.setHandler(this.search,this);
	},
	search: function(o,e){
		var text = this.app.viewport.field.getValue();
		if(text){
			var target = this.app.viewport.mainPanel;
			var ds = Ext.app.Data.ListStore.create({url: 'optimized_search/list_by_words'},{keywords:text,center_uniq:'check'});
			ds.on('beforeload',function(store,options){
				if(store.getTotalCount() > 0){
					options.params['total'] = store.getTotalCount();
				}
			});
			var p = target.add(Ext.app.Grid.List.create(text,ds,true));
			target.setActiveTab(p);
			// ====================
			var sm = p.getSelectionModel();
			var searchRefinement = function(){
				var rows = sm.getSelections();
				var keywords = rows.map(function(record){
					return record.get('center');
				}).join(' ');
				var refinement_ds = Ext.app.Data.SentenceStore.create({url: 'optimized_search/sentences_by_words'},{keywords:keywords});
				refinement_ds.on('beforeload',function(store,options){
					if(store.getTotalCount() > 0){
						options.params['total'] = store.getTotalCount();
					}
				});
				var refinement_p = target.add( Ext.app.Grid.KWICGrid.create(String.format('Search refinement ({0})',text),refinement_ds));
				target.setActiveTab(refinement_p,target);
				Ext.app.Grid.addAroundSearchMenu(refinement_p,target);
				refinement_ds.load({params:{start:0, limit:25}});
			}
			var refinement = new Ext.Toolbar.Button({
				iconCls: 'find',
				disabled: true,
				handler: searchRefinement,
				text: "Search refinement"
			});
			sm.on({
				rowselect: function(){
					if(refinement.disabled){
						refinement.enable();
					}
				},
				rowdeselect: function(){
					if(!sm.hasSelection()){
						refinement.disable();
					}
				},
				scope: this
			});
			var ds = p.getStore();
			ds.on({
				load: function(){
					if(!sm.hasSelection()){
						refinement.disable();
					}
				} 
			});
			var pbar = p.getBottomToolbar();
			pbar.add('-',' ',refinement);
			// ====================
			ds.load({params:{start:0, limit:25}});
//			this.app.viewport.field.reset();
		}
	}
});

